
-- EliteMatchSeekView

local fileName = string.getModeName(...)
local EliteMatchSeekView = class(fileName, app.mvc.ViewBase)

local IconRender = require("app.widget.renders.IconRender")
local TeamMatchListPanel = require("app.team.views.TeamMatchListPanel")
local NewTeamMemberPanel = require("app.team.views.NewTeamMemberPanel")
local EliteMatchTeamPanel = import(".panels.EliteMatchTeamPanel")
local AvatarFactory = require("app.public.avatar.AvatarFactory")
local EliteMatchChampionRender = import(".renders.EliteMatchChampionRender")
local CrossServerEliteMatchHelper = import(".CrossServerEliteMatchHelper")

EliteMatchSeekView.VIEW_ROOT_RES = Res.CSEliteMatchSeekScene

function EliteMatchSeekView:init()
    self._ui.Button_close:addClickEventListener(function()
		executeFunc(self._onCloseView)
    end)   
    --left
    self._championPanel = EliteMatchChampionRender.create(self._ui.left)

    -- top
    self._topPanel = self._ui["Panel/Panel_seek/Panel_top"]
    self._autoBtnText = self._topPanel:getChildByName("selected_tlt")
    self._autoBtn = self._topPanel:getChildByName("selected_btn")
    self._autoBtn:addClickEventListener(handler(self, self._onClickAutoBtn))
    local rankBtn = self._topPanel:findChild("Panel_bg/rank_btn")
    rankBtn:addClickEventListener(function()
        -- 查看排行榜（排行榜id等于playid）
        UIHandler:handleMessage({id = Constant.FUNC_TYPE_RANK, mode = "open", rankingId = self._curPlayId})
    end)

    --bottom
    self._bottomPanel = self._ui["Panel/Panel_seek/Panel_bom"]
    local bomPanel = self._bottomPanel
    self._createBtn = bomPanel:getChildByName("Button_enter")
    self._createBtnName = self._createBtn:getChildByName("name")
    self._bomText = bomPanel:getChildByName("Text")
    self._arenaSingleBtn = bomPanel:getChildByName("Button_found")
    self._duelSingleBtn = bomPanel:getChildByName("Button_one")
    self._duelSingleBtnName = self._duelSingleBtn:getChildByName("name")
    self._eliteMatchTips = bomPanel:findChild("Panel_icon/icon_text")

    self._arenaSingleBtn:addClickEventListener(function()
        -- 竞技场单人匹配
        self:_startMatch()
    end)

    self._duelSingleBtn:addClickEventListener(function()
        -- 决斗赛 单人匹配/取消匹配
        if L("ui_csd_776") == self._duelSingleBtnName:getString() then           
            --先判断是否调整过随从
            local haveChangePartner = UD:getValueFromGenericByKey("eliteMatchChangePartner")
            if haveChangePartner then
                --如果调整过随从
                self:_startMatch()
            else
                --没有调整过
                UD:saveGeneric("eliteMatchChangePartner",true)
                local confirmDialog = display.newConfirmDialog(L("duelGametips34"),
                    function() -- 确定
                        app:sendMsg("PvpEliteController", "openEliteMatchDuelTeamView")
                    end,
                function() --取消
                    
                end)
                UIHandler:addPopDialog( confirmDialog )
            end
        elseif L("lua_code_text_110") == self._duelSingleBtnName:getString() then
            executeFunc(self._onOperate, "CombatCross_cancelMatch")
        end
    end)

    self._createBtn:addClickEventListener(function()
        -- 创建队伍/匹配/取消匹配
        if L("champion_team7") == self._createBtnName:getString() then
            executeFunc(self._onOperate, "CombatCross_createTeam", self._curTarget )
        elseif L("lua_code_text_102") == self._createBtnName:getString() then
            if self._isLeader then
                self:_startMatch(true)
            else
                local dlg = display.newConfirmDialog( L("team_text6"),
                    function() -- 确定
                        app:sendMsg("TeamModel", "reqQuitTeam")
                    end)
                UIHandler:addPopDialog( dlg )
            end
        elseif L("lua_code_text_110") == self._createBtnName:getString() then
            executeFunc(self._onOperate, "CombatCross_cancelMatch")
        end
    end)
   
    local searchNode = bomPanel:getChildByName("Button_tips")
    searchNode:getChildByName("Panel_1"):addClickEventListener(function()
        -- 玩法详情
        executeFunc(self._onOperate, "EliteMatch_search", self._curPlayId)
    end)

    local iconPanel = bomPanel:getChildByName("Panel_icon")
    self._succIconRenders = {}
    self._succIconText = {}
    for i = 1, 3 do
        local render = IconRender.create(iconPanel:getChildByName("icon"..i))
        render:setTipEnable(true)
        self._succIconRenders[i] = render
        self._succIconText[i] = iconPanel:getChildByName("Text_"..i)
    end
    self._failIconPanel = iconPanel:getChildByName("Panel_fail")
    local render = IconRender.create(self._failIconPanel:getChildByName("icon6"))
    render:setTipEnable(true)
    self._failIconRender = render
    self._failIconText = self._failIconPanel:getChildByName("Text_6")

    -- center team
    self._teamListPanel = TeamMatchListPanel.create(self._ui.Panel_tuijian)
    self._teamPanel = self._ui["Panel/Panel_seek/Panel_team"]
    self._teamData = self._teamPanel:getChildByName("Panel_data")
    
    local dataPanel = self._teamData
    self._btnApply = dataPanel:getChildByName("Button_apply")
    self._applyDot = self._btnApply:getChildByName("dotNew")
    self._btnLeave = dataPanel:getChildByName("Button_leave")
    self._btnSet = dataPanel:getChildByName("Button_set")
    self._panelNum = dataPanel:getChildByName("Panel_num")
    self._totalPow = self._panelNum:getChildByName("combat_num")
    self._powDesc = self._panelNum:getChildByName("combat_tlt")
    self._powDesc:setString( L("champion_team8") )
    self._btnApply:addClickEventListener(function()
        -- 展开申请列表
        executeFunc(self._onOperate, "EliteMatch_showApplyList")
        self:refreshNewApplyerFlag( false )
    end)
    self._btnLeave:addClickEventListener(function()
        -- 退出队伍
        local creataeTeamDialog = display.newConfirmDialog( L("champion_team9"),
            function() -- 确定
                executeFunc(self._onOperate, "EliteMatch_quitTeam")
            end)
        UIHandler:addPopDialog( creataeTeamDialog )
    end)
    self._btnSet:addClickEventListener(function()
        -- 打开己方队伍设置
        executeFunc(self._onOperate, "EliteMatch_TeamSettingUI", { 2 } ) -- "我"的设置
    end)

    -- 开启时间
    self._tipsTime = self._topPanel:getChildByName("tips_time")
    self._textTime = self._tipsTime:getChildByName("text")
    
    -- center seek
    self._seekPanel = self._ui["Panel/Panel_seek/Panel_pipei"]
    local aniPanel = self._seekPanel:getChildByName("Panel_ani")
    local di = aniPanel:getChildByName("di")
    di:retain()
    di:removeFromParent()

    local mask = aniPanel:getChildByName("mask")
    mask:retain()
    mask:removeFromParent()

    local cilpNode = cc.ClippingNode:create()
    cilpNode:setAlphaThreshold(0.5)
    cilpNode:setPosition(0, 0)
    cilpNode:addChild(di)
    cilpNode:setStencil(mask)
    cilpNode:addTo(aniPanel, -1)

    di:release()
    mask:release()

    -- center no
    self._noPanel = self._ui["Panel/Panel_seek/Panel_no"]

    self._curPlayId = Enums.TeamTarget.eliteMatchArena --当前玩法Id 

    self:registerViewEvent({
        {name = ViewEvent.CSElite_CrossCombatMatchUpdate, callback = handler(self, self.updateSeekInfo)},
        {name = ViewEvent.CSElite_TeamListUpdate, callback = handler(self, self.refreshTeamList)},
        {name = ViewEvent.CSElite_onBattlePartnerChange, callback = handler(self, self.refreshDuelTeamPanel)},
        {name = ViewEvent.CSElite_LastSeasonChampionInfo, callback = handler(self, self.updateLastSeasonChampionInfo)}
    })
end

function EliteMatchSeekView:show()
    self:setVisible(true)
end

-- 开始匹配
function EliteMatchSeekView:_startMatch(isOp)
    if isOp then
        executeFunc(self._onOperate, "reqCombatCrossTeamMatch")
    else
        UD.csEliteMatch:C2S_CombatCrossMatch(self._curPlayId)
    end
end

function EliteMatchSeekView:_onClickAutoBtn()
    local isBright = self._autoBtn:isBright()
    self._autoBtn:setBright(not isBright)
    if self._team then
        executeFunc(self._onOperate, "autoRecruit", self._curPlayId, isBright)
    else
        executeFunc(self._onOperate, "autoApply", self._curPlayId, isBright)
    end
end

function EliteMatchSeekView:_tick(dt)
    if not self._curOpenTime and not self._nextOpenTime then
        self._tipsTime:setVisible(false)
        return
    end
    function calcTime()
        self._isTimeOpen = false
        local serverTime = app.session:getServerTime()
        if self._curOpenTime.starttime and self._curOpenTime.endtime then
            if serverTime < self._curOpenTime.starttime then
                self._remainedTime = self._curOpenTime.starttime - serverTime
            elseif serverTime > self._curOpenTime.endtime then
                -- 过了今天的开启时间
                if self._nextOpenTime then
                    self._remainedTime = self._nextOpenTime - serverTime
                end
            else
                self._remainedTime = self._curOpenTime.endtime - serverTime
                self._isTimeOpen = true
            end
        end
    end
    if not self._remainedTime or self._remainedTime <= 0 then 
        calcTime()
    end
    self._remainedTime = self._remainedTime - 1
    local str = self._isTimeOpen and L("lua_code_text_108") or L("lua_code_text_154")
    local day, time = TimeUtil.secondsToStr(self._remainedTime, 1)
    local offlineStr = ""
    if 0 < day then
        offlineStr = string.format(L("lua_code_text_374"), day)
    end
    offlineStr = offlineStr .. time
    self._textTime:setString(string.format(str, offlineStr))
    self._tipsTime:setVisible(true)
end

function EliteMatchSeekView:updateSeekView()
    if self._data then
        local data = self._data
        self._curPlayId = data   
        self._curTarget = app:getInst("TeamModel"):getTeamTargetById(data)
        self._playInfo = UD.csEliteMatch:getPlayInfoById(self._curPlayId)
        self._curOpenTime = CrossServerEliteMatchHelper:getCurOpenTimeById(self._curPlayId)
        self._nextOpenTime = CrossServerEliteMatchHelper:getNextOpenTimeById(self._curPlayId)
        -- 更新top
        local targetConf = GD:queryTeamTargetById(self._curPlayId)
        local iconPath = string.format(Res.TeamTargetPath, targetConf.iconPath)
        self._topPanel:getChildByName("icon"):loadTexture(iconPath)
        self._topPanel:getChildByName("name"):setString(L(targetConf.name))
        self._topPanel:getChildByName("desc"):setString(L(targetConf.desc))
        self._maxNum = tonumber(targetConf.maxNum)
        -- 注册定时器
        if self._cronsIdx then
            scheduler.cancelCron(self._cronsIdx)
            self._cronsIdx = nil
        end
        self._cronsIdx = scheduler.newCron(handler(self, self._tick), 1, true)
        self:_tick()
        -- 底部奖励
        local rewards, punishs = CrossServerEliteMatchHelper:getLootRewardByPlayId(self._curPlayId, self._playInfo.lv)
        for i = 1, 3 do
            local render = self._succIconRenders[i]
            local text = self._succIconText[i]
            local value = rewards[i]
            if value then
                render:setVisible(true)
                text:setVisible(true)
                text:setString(value.textStr)
                text:setTextColor(value.textColor)
                local reward = UD:parseRewardToBagItem(value.data)
                render:setData(reward)  
                render:setNumString(reward:getAmount())
                if reward:getId() == Constant.LightForgeGoldId then
                    local contents = CrossServerEliteMatchHelper:getExtraTipsContent(reward, self._curPlayId)
                    render:setExtraTipsContents(contents)
                end
            else            
                render:setVisible(false)
                text:setVisible(false)
            end
        end
        if punishs then
            self._failIconPanel:setVisible(true)
            local punish = UD:parseRewardToBagItem(punishs.data)
            self._failIconRender:setData(punish)
            self._failIconRender:setNumString("-"..punish:getAmount())  
            self._failIconRender:setNumberColor(display.COLOR_RED) 
            self._failIconText:setString(punishs.textStr)
            self._failIconText:setTextColor(punishs.textColor)        
        else
            self._failIconPanel:setVisible(false)
        end
        --icon pos
        local render = self._succIconRenders[#rewards+1]
        local posX
        if not render then
            render = self._succIconRenders[3]
            local iconWidth = render:getContentSize().width*render:getScaleX()
            posX = render:getPositionX() + iconWidth + 5
        else
            posX = render:getPositionX() + 5
        end 
        if punishs then
            self._failIconPanel:setPositionX(posX)
        end
        
        self._teamListPanel:setVisible(false)
        self._teamPanel:setVisible(false)
        self._seekPanel:setVisible(false)
        self._noPanel:setVisible(false)
        self._arenaSingleBtn:setVisible(false)
        self._duelSingleBtn:setVisible(false)
        self._autoBtn:setVisible(false)
        self._autoBtnText:setVisible(false)
        self._createBtn:setVisible(false)
        display.setBtnTouchEnable(self._createBtn, true)

        -- 匹配面板
        if self._curPlayId == Enums.TeamTarget.eliteMatchArena then
            self._teamMemberPanel = NewTeamMemberPanel.create(self._teamPanel:getChildByName("player"))
            self:_updateArenaPanel()
        elseif self._curPlayId == Enums.TeamTarget.eliteMatchDuel then
            self._teamMemberPanel = EliteMatchTeamPanel.create(self._teamPanel:getChildByName("player"))
            self:_updateDuelPanel()
        end
        self._teamMemberPanel:registerOnOperate(function(op, ...)
            executeFunc(self._onOperate, op, ...)
        end)
    end
end

-- 竞技场匹配面板
function EliteMatchSeekView:_updateArenaPanel()
    self._teamPanel:setVisible(false)
    self._teamListPanel:setVisible(false)
    self._seekPanel:setVisible(false)
    self._autoBtn:setVisible(false)
    self._autoBtnText:setVisible(false)
    display.setBtnTouchEnable(self._createBtn, true)
    self:pauseAction()

    if UD.csEliteMatch:getState() == "idle" then
        executeFunc(self._onOperate, "refreshEliteMatchMemberList")
    else
        self:setSeekPanel()
        self._arenaSingleBtn:setVisible(false)
        self._createBtn:setVisible(true)
        self._createBtnName:setString(L("lua_code_text_110"))
        -- 备战中
        if UD.csEliteMatch:getState() == "prepare" then
            self._seekPanel:getChildByName("text"):setString(L("challengeTips6"))
            display.setBtnTouchEnable(self._createBtn, false)
        end
    end
end

-- 决斗赛匹配面板
function EliteMatchSeekView:_updateDuelPanel()
    self._teamPanel:setVisible(false)
    self._seekPanel:setVisible(false)
    display.setBtnTouchEnable(self._duelSingleBtn, true)
    self:pauseAction(false)
    if UD.csEliteMatch:getState() == "idle" then
        executeFunc(self._onOperate, "QueryNowTeamInfo")
    else
        self:setSeekPanel()
        self._duelSingleBtn:setVisible(true)
        self._duelSingleBtnName:setString(L("lua_code_text_110"))
        -- 备战中
        if UD.csEliteMatch:getState() == "prepare" then
            self._seekPanel:getChildByName("text"):setString(L("challengeTips6"))
            display.setBtnTouchEnable(self._duelSingleBtn, false)
        end
    end
end

function EliteMatchSeekView:setSeekPanel()
    self._seekPanel:setVisible(true)
    self:playAction(nil, true)  
    local teammates = UD.csEliteMatch:getTeammates()
    local count = #teammates -- 暂时不考虑大于3的情况
    local midX = 365
    local intervalX = 90
    local midNum = (count + 1) / 2
    for i = 1, 3 do
        local icon = self._seekPanel:getChildByName("icon_"..i)
        local img = icon:getChildByName("icon_img")
        img:setVisible(false)
        if i <= count then 
            icon:setVisible(true)
            icon:setPositionX(midX - (midNum - i) * intervalX)

            AvatarFactory.getOrCreateHeroIconPath(teammates[i], function(path)
                if not cc.isDead(self) then
                    img:loadTexture(path)
                    img:setVisible(true)
                end
            end)
        else
            icon:setVisible(false)
        end
    end
end

function EliteMatchSeekView:refreshTeamMemberList(team, isNewApplyerFlag)
    if self._curPlayId ~= Enums.TeamTarget.eliteMatchArena then return end  
    -- 未匹配状态
    if UD.csEliteMatch:getState() ~= "idle" then return end

    self._teamPanel:setVisible(false)
    self._teamListPanel:setVisible(false)
    self._autoBtn:setVisible(false)
    self._autoBtnText:setVisible(false)
    local isAuto = false
    local isShowAuto = true
    self._team = team
    if team and team:isInTeam(UD.player.uid) then
        -- 有队伍
        self._teamPanel:setVisible(true)
        self._teamMemberPanel:setVisible(true)
        self._teamData:setVisible(true) 

        self._teamMemberPanel:setData(team)
        -- 玩法最大人数
        local maxNum = self._maxNum
        -- 刷新超限制人数禁止标志
        self._teamMemberPanel:refreshForbiddenIconStatus(maxNum)

        -- 队伍真实玩家的战斗力
        local teamCombatPower = team:getTeamTotalCapacity()
        self._totalPow:setString(teamCombatPower)
        -- 居中对齐
        display.setNodesMiddle(self._panelNum, nil, self._powDesc, self._totalPow)
        
        self:refreshNewApplyerFlag(isNewApplyerFlag)
    
        self._isLeader = team:isLeader(UD.player.uid)
        self:updateTeamBtn(self._isLeader)
        isAuto = team:isAutoRecruit(self._curTarget.id)
        isShowAuto = self._isLeader
    else
        executeFunc(self._onOperate, "refreshTeamList", self._curPlayId)
        isAuto = self._curTarget:isAutoApply()
    end
    -- 自动申请/招募按钮
    self._autoBtn:setVisible(isShowAuto)
    self._autoBtnText:setVisible(isShowAuto)
    if isShowAuto then
        self._autoBtnText:setString(team and L("lua_code_text_393") or L("lua_code_text_167"))
        self._autoBtn:setBright(not isAuto)
    end
    if team and team:isInTeam(UD.player.uid) then
        self._createBtn:setVisible(true)
        self._createBtnName:setString(L("lua_code_text_102"))
        self._arenaSingleBtn:setVisible(false)
    else
        self._createBtn:setVisible(true)
        self._createBtnName:setString(L("champion_team7"))
        self._arenaSingleBtn:setVisible(true)
    end
end

function EliteMatchSeekView:refreshTeamTarget(target)
    -- 未匹配状态
    if UD.csEliteMatch:getState() ~= "idle" then return end

    if not cc.isDead(self._teamListPanel) then
        self._teamListPanel:refreshTarget(target)
    end
end

function EliteMatchSeekView:refreshTeamList(eventName, info)
    -- 未匹配状态
    if UD.csEliteMatch:getState() ~= "idle" then return end

    if not cc.isDead(self._teamListPanel) then
        self._teamListPanel:setVisible(true)
        self._teamListPanel:setData(info)
    end
end

function EliteMatchSeekView:refreshDuelTeamPanel(eventName, info)
    -- 未匹配状态
    if UD.csEliteMatch:getState() ~= "idle" then return end

    if not cc.isDead(self._teamMemberPanel) then
        self._teamPanel:setVisible(true)
        self._teamMemberPanel:setVisible(true)
        self._teamMemberPanel:setData(info)
        self._teamData:setVisible(true)
        self._btnApply:setVisible(false)
        self._btnLeave:setVisible(false)
        self._btnSet:setVisible(false)
        self._duelSingleBtn:setVisible(true)
        self._duelSingleBtnName:setString(L("ui_csd_776"))
        if info then
            local teamCombatPower = info:getTeamCombatPower()
            self._totalPow:setString(teamCombatPower)
            -- 居中对齐
            display.setNodesMiddle(self._panelNum, nil, self._powDesc, self._totalPow)
            self._panelNum:setVisible(true)
        else
            self._panelNum:setVisible(false)
        end
    end
end

-- 刷新新申请者new标记状态
function EliteMatchSeekView:refreshNewApplyerFlag(visible)
    self._applyDot:setVisible(visible)
end

-- 更新队伍按钮状态
function EliteMatchSeekView:updateTeamBtn(isLeader)
    if isLeader then
        self._btnApply:setVisible(true)
    else
        self._btnApply:setVisible(false)
    end
end

function EliteMatchSeekView:updateAutoApplyStatus(teamTarget)
    teamTarget = teamTarget or self._curTarget
    if teamTarget == self._curTarget then
        self._autoBtn:setBright(not teamTarget:isAutoApply())
    end
end

function EliteMatchSeekView:updateAutoRecruitStatus(teamTarget)
    teamTarget = teamTarget or self._curTarget
    if teamTarget == self._curTarget then
        self._autoBtn:setBright(not teamTarget:isAutoRecruit())
    end
end

-- 刷新推荐队伍的申请状态
function EliteMatchSeekView:refreshTeamListApply(team)
    -- 未匹配状态
    if UD.csEliteMatch:getState() ~= "idle" then return end

    if not cc.isDead(self._teamListPanel) then
        self._teamListPanel:refreshTeamApply(team)
    end
end

function EliteMatchSeekView:updateSeekInfo(eventName)
    if self._curPlayId == Enums.TeamTarget.eliteMatchArena then
        self:_updateArenaPanel()
    elseif self._curPlayId == Enums.TeamTarget.eliteMatchDuel then
        self:_updateDuelPanel()
    end
end

function EliteMatchSeekView:updateLastSeasonChampionInfo(eventName, info)
    if not info then return end
    if not cc.isDead(self._championPanel) then
        self._championPanel:setData(info)
    end
end

function EliteMatchSeekView:onOperate(cb)
    self.super.onOperate(self, cb)

    self._teamListPanel:onOperate(cb)
end

function EliteMatchSeekView:onExit()
    self.super.onExit(self)
    if self._cronsIdx then
        scheduler.cancelCron(self._cronsIdx)
        self._cronsIdx = nil
    end
end

return EliteMatchSeekView